import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:flutter_ywt/config/environment_manager.dart';
import 'package:flutter_ywt/config/router_manager.dart';
import 'package:flutter_ywt/config/theme/size.dart';
import 'package:flutter_ywt/constant/app_data.dart';
import 'package:flutter_ywt/constant/picker_data.dart';
import 'package:flutter_ywt/http/repository_login.dart';
import 'package:flutter_ywt/model/login/login_data.dart';
import 'package:flutter_ywt/store/index.dart';
import 'package:flutter_ywt/store/store_login.dart';
import 'package:flutter_ywt/store/store_menu.dart';
import 'package:flutter_ywt/utils/app_util.dart';
import 'package:package_info/package_info.dart';

import '../../../constant/menu_data.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  var scaffoldKey = GlobalKey<ScaffoldState>();
  String version = "0";
  String buildNumber = "0";
  List listCompanyName = List();
  List listCompanyCode = List();
  @override
  void initState() {
    super.initState();
    //设置全局路由 上下文
    Routers.setContext(context);
    //初始化包名
    _initPackageInfo();
    //初始化公司列表
    yh_company.forEach((value) {
      listCompanyName.add(value['longName']);
      listCompanyCode.add(value['compCode']);
    });

  }

  Future<void> _initPackageInfo() async {
    final PackageInfo info = await PackageInfo.fromPlatform();
    setState(() {
      buildNumber = info.buildNumber;
      version = info.version;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      resizeToAvoidBottomInset: false, //键盘弹起，不重绘布局（重绘布局，会导致底部图片上弹）
      body: Stack(
        fit: StackFit.expand, //未定位的元素，会沾满剩余的空间
        children: <Widget>[
          Container(
            color: Colors.white,
            child: ListView(
              children: <Widget>[
                SizedBox(height: size60),
                InkWell(
                  child: Image.asset(
                    "assets/images/ic_logo.png",
                    width: size60,
                    height: size60,
                  ),
                  onTap: _logoClick,
                ),

                SizedBox(height: size40),
                //输入框
                loginForm(context,listCompanyName ,listCompanyCode),
                SizedBox(height: size20),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: SizedBox(),
                    ),
                    GestureDetector(
                      child: Text(
                        "找回密码",
                        style: TextStyle(
                            color: Theme.of(context).primaryColorDark),
                      ),
                      onTap: _toTest,
                    ),
                    SizedBox(width: size20),
                  ],
                ),
              ],
            ),
          ),
          Positioned(
              bottom: 0,
              left: 0, //指定left和right：相当于指定了宽。宽必须指定，不然图片无法正确绘制
              right: 0,
              child: Image.asset("assets/images/ic_login_bottombacground.png")),
          Positioned(bottom: size10, left: size10, child: Text(Environment.tag + " 版本号：2020.11.05 - "  + version))
        ],
      ),
    );
  }
  _logoClick() {
    //路由传参给 下个页面
    Future<dynamic> result = Routers.push(RouteName.test_image,  {"title": "应用宝"});
    result.then((value) => {
      //接收上个页面的返回值
      print(value.toString())
    });
  }

  _toTest() {
    //路由传参给 下个页面
    Future<dynamic> result = Routers.push(RouteName.test_map,  {"title": "应用宝"});
    result.then((value) => {
      //接收上个页面的返回值
      print(value.toString())
    });
  }

}



Widget loginForm(BuildContext context, List listCompanyName, List listCompanyCode) {
  GlobalKey _formKey = new GlobalKey<FormState>();
  var controller = TextEditingController();
  controller.text = "美团外卖";
   String compCode = "meituan";
   String userName = "app";
   String password = "app";

  _commit() async {
    //调用form的save方法 -> 自动调控件的save方法
    (_formKey.currentState as FormState).save();
    AppUtil.showLoading(context, "正在登陆");
    Map<String, dynamic> queryParameters = Map();
    queryParameters['password'] = password;
    queryParameters['username'] = userName;
    LoginData data = await LoginRepository.loginPost(queryParameters);
    if(data.dioError != null) {
      //隐藏对话框
      Navigator.pop(context);
      return;
    }
    //保存token
    AppData.token = data.token;
    //保存登陆信息
    Store.value<StoreLogin>().mData = data;
    //赋值菜单全局管理
    data.permissions.removeWhere((element) => element.name == APP_MENU);
    Store.value<StoreMenu>().mData = data.permissions;

    //隐藏对话框
    Navigator.pop(context);
    //到主界面
    Routers.push(RouteName.main);

  }
  _showPickerModal() {
    Picker(
        adapter: PickerDataAdapter<String>(pickerdata: listCompanyName),
        hideHeader: false,
        height: size200,
        headerDecoration: BoxDecoration(color: Colors.white10),
        selectedTextStyle: TextStyle(fontSize: display2),
        squeeze: 1,//文字间距的倍数
        onConfirm: (Picker picker, List value) {
          compCode = listCompanyCode[value[0]];
          controller.text = listCompanyName[value[0]];
        }
    ).showModal(context);
  }

  //登陆表单
  return Form(
    key: _formKey,
    child: Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.fromLTRB(size20, 0, size20, 0),
          height: size40,
          child: TextFormField(
            controller: controller,
            maxLength: 10,
            maxLines: 1,
            readOnly: true,
            onTap: _showPickerModal,
            decoration: InputDecoration(
              enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black45)),
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black45)),
              counterText: "",
              prefixIcon: Icon(Icons.table_chart, color: Colors.black54),
              hintText: "请选择企业",
            )
          ),
        ),
        SizedBox(height: size20),
        Container(
          margin: EdgeInsets.fromLTRB(size20, 0, size20, 0),
          height: size40,
          child: TextFormField(
            initialValue: userName,
            autofocus: false,
            autovalidate: true,
            maxLength: 10,
            maxLines: 1,
            decoration: InputDecoration(
              enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black45)),
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black45)),
              counterText: "",
              prefixIcon: Icon(Icons.person, color: Colors.black54),
              hintText: "工号",
              // hintStyle: TextStyle(color: Colors.black),
            ),
            onSaved: (val) {
              userName = val;
            },
          ),
        ),
        SizedBox(height: size20),
        Container(
          margin: EdgeInsets.fromLTRB(size20, 0, size20, 0),
          height: size40,
          child: TextFormField(
            autofocus: false,
            initialValue: password,
            autovalidate: true,
            maxLength: 10,
            maxLines: 1,
            obscureText: true,
            decoration: InputDecoration(
              enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black45)),
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.black45)),
              counterText: "",
              prefixIcon: Icon(Icons.lock, color: Colors.black54),
              hintText: "密码",
            ),
            onSaved: (val) {
              password = val;
            },
          ),
        ),
        SizedBox(
          height: size40,
        ),
        RaisedButton(
            padding: EdgeInsets.fromLTRB(size100, 0, size100, 0),
            onPressed: _commit,
            child: Text("登录")),
      ],
    ),
  );


}


